package com.example.campusforumapi.controller;

import com.example.campusforumapi.entity.Department;
import com.example.campusforumapi.entity.Role;
import com.example.campusforumapi.entity.User;
import com.example.campusforumapi.entity.UserRole;
import com.example.campusforumapi.service.UserRoleService;
import com.example.campusforumapi.service.UserService;
import com.example.campusforumapi.util.PageResult;
import com.example.campusforumapi.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/userroles")
public class UserRoleController extends BaseController{
    @Autowired
    private UserRoleService userRoleService;

    //    查询所有角色信息记录
    @GetMapping("/getRoles")
    public Result getRoles() {
        List<Role> roleList = userRoleService.getRoles();
        return Result.success(roleList);
    }

    /*
     * 按条件  分页查询
     * */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize
            , Integer roleId){

        //        查询并封装分页结果集
        PageResult rolePage = userRoleService.getUserRolePage(page,pageSize,roleId);

        return Result.success(rolePage);
    }

    //    删除一条记录
    @DeleteMapping ("/delete/{userIds}/{roleIds}")
    public Result delete(@PathVariable List<Integer> userIds,@PathVariable List<Integer> roleIds){
        userRoleService.delUserRole(userIds,roleIds);
        return Result.success();
    }

    //    新增一条记录
    @PostMapping ("/insert")
    public Result insert(@RequestBody UserRole userRole){
        if(StringUtils.isEmpty(userRole.getUserId()) || StringUtils.isEmpty(userRole.getRoleId())){
            return Result.error("用户ID及角色ID不能为空");
        }else if(userRoleService.findsameUserId(userRole.getUserId())<1){
            return Result.error("该用户ID不存在，请先注册!");
        }
        else if(userRoleService.insertUserRole(userRole) > 0){
            return Result.success("插入成功");
        }else{
            return Result.error("该用户名与角色关系已存在");
        }

    }

    //    修改一条记录
    @PutMapping("/update")
    public Result update(@RequestBody UserRole userRole){
        if(userRoleService.updUserRole(userRole) > 0){
            return Result.success("修改成功");
        }else{
            return Result.error("修改失败");
        }

    }

}
